#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

/*

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                      void *(*start_routine) (void *), void *arg);


int pthread_join(pthread_t thread, void **retval);
void pthread_exit(void *retval);

// pthread_attr_t attr;
// int pthread_attr_init(pthread_attr_t *attr);
// int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);
// int pthread_attr_destroy(pthread_attr_t *attr);


// int pthread_detach(pthread_t thread);

// pthread_t pthread_self(void);

int pthread_cancel(pthread_t thread);
int pthread_setcancelstate(int state, int *oldstate);
int pthread_setcanceltype(int type, int *oldtype);
*/

void routine(void *arg)
{
    printf("接受到取消请求之后，先执行routine函数\n");
}

void *start_routine(void *arg)
{
    // 取消之前先执行routine  压栈 取消例程函数
    pthread_cleanup_push(routine, NULL);
    int count = 0;
    while (count < 3)
    {
        printf("start_routine 线程\n");
        sleep(1);
        count++;
    }
    // 如果子线程没有接收到取消请求结束之前要不要运行routine函数 弹栈 取消例程函数
    // pthread_cleanup_pop(0);
    pthread_cleanup_pop(1); // 1表示执行取消例程函数 0表示不执行取消例程函数
}

int main()
{
    int count = 1;

    printf("main\n");

    // 创建一个线程
    pthread_t thread;
    int res_create = pthread_create(&thread, NULL, start_routine, &count);
    printf("res_create=%d\n", res_create);

    sleep(10);
    // 发起取消线程请求
    int ret_cancel = pthread_cancel(thread);
    printf("ret_cancel=%d\n", ret_cancel);

    // 等待子线程退出(阻塞的)
    int ret_join = pthread_join(thread, NULL); // 0 成功 -1 失败
    printf("ret_join=%d\n", ret_join);

    return 0;
}
